/*
 * <<
 *  Davinci
 *  ==
 *  Copyright (C) 2016 - 2019 EDP
 *  ==
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *        http://www.apache.org/licenses/LICENSE-2.0
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *  >>
 *
 */

package com.sdkj.dspservice.modules.report.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sdkj.dspservice.common.base.controller.BaseController;
import com.sdkj.dspservice.common.react.AntdProResult;
import com.sdkj.dspservice.modules.report.entity.Source;
import com.sdkj.dspservice.modules.report.service.SourceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.lang.reflect.UndeclaredThrowableException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据源控制器
 * @author tm
 */
@Api(value = "/report/source", tags = "数据源管理")
@ApiResponses(@ApiResponse(code = 404, message = "sources not found"))
@RestController
@RequestMapping(value = "${project-config.apiUrl}/${project-config.version}/report/source")
public class SourceController extends BaseController {

    @Autowired
    private SourceService sourceService;

    /**
     * 获取详情
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "获取详情")
    @GetMapping(value = "get")
    public AntdProResult get(String id) {
        AntdProResult result = new AntdProResult();
        Source source = sourceService.getById(id);
        result.success(source);
        return result;
    }

    /**
     * 获取列表
     *
     * @param source
     * @return
     */
    @ApiOperation(value = "获取列表")
    @GetMapping(value = "list")
    public AntdProResult list(Source source) {
        AntdProResult result = new AntdProResult();
        Page<Source> sourcesPage = sourceService.page(new Page<>(source.current, source.pageSize), new QueryWrapper<>(source));
        result.success(sourcesPage);
        return result;
    }

    /**
     * 创建
     *
     * @param source
     * @return
     */
    @ApiOperation(value = "创建")
    @PostMapping(value = "save")
    public AntdProResult save(@Valid @RequestBody Source source) {
        AntdProResult result = new AntdProResult();
        source.setDatabaseType(source.getDatabaseType());
        sourceService.saveOrUpdate(source);
        return result;
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "删除")
    @RequestMapping(value = "remove")
    public AntdProResult delete(String id) {
        AntdProResult result = new AntdProResult();
        sourceService.removeById(id);
        return result;
    }

    /**
     * 测试数据库连接
     *
     * @param source
     * @return
     */
    @ApiOperation(value = "测试数据库连接", consumes = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping(value = "testSource", consumes = MediaType.APPLICATION_JSON_VALUE)
    public AntdProResult testSource(@Valid @RequestBody Source source) {
        AntdProResult result = new AntdProResult();
        boolean testResult = false;
        try {
            testResult = sourceService.testSource(source);
            result.setSuccess(testResult);
        } catch (UndeclaredThrowableException ue){
            ue.printStackTrace();
            String[] errors = String.valueOf(ue.getUndeclaredThrowable()).split(":");
            result.error(AntdProResult.VALIDATOR_ERROR, errors.length > 1 ? errors[1] : errors[2]);
        }catch (Exception e) {
            e.printStackTrace();
            result.error(AntdProResult.SYSTEM_ERROR, "未知错误");
        }
        return result;
    }

    /**
     * 获取数据源select列表
     *
     * @param source
     * @return
     */
    @ApiOperation(value = "获取select列表")
    @GetMapping(value = "listForSelect")
    public AntdProResult listForSelect(Source source) {
        AntdProResult result = new AntdProResult();
        List<Source> sourceList = sourceService.list(source);
        // 转换为{label:xxx,value:xxx}
        List<Map<String, Object>> mapList = new ArrayList<>();
        for(Source s : sourceList){
            Map<String, Object> map = new HashMap<>(2);
            map.put("label", s.getName());
            map.put("value", s.getId());
            mapList.add(map);
        }
        result.success(mapList);
        return result;
    }

    /**
     * source 的数据库
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "获取数据库名称列表")
    @GetMapping("getDatabaseNameList")
    public AntdProResult getDatabaseNameList(String id) {
        return new AntdProResult().success(sourceService.getDatabaseNameList(id));
    }

    /**
     * 获取当前数据库的数据表名称列表
     *
     * @param id sourceId
     * @return
     */
    @ApiOperation(value = "获取当前数据库的数据表名称列表")
    @GetMapping("getTableNameList")
    public AntdProResult getTableNameList(String id) {
        return new AntdProResult().success(sourceService.getTableNameList(id));
    }

//    /**
//     * 获取数据表结构
//     *
//     * @param id sourceId
//     * @return
//     */
//    @ApiOperation(value = "获取当前数据库的数据表名称列表")
//    @GetMapping("getTableInfo")
//    public AntdProResult getTableInfo(String id, String tableName) {
//
//        return new AntdProResult().success(columnList);
//    }

}
